<?php

function getAreas($circles){
    $c_arr = explode(",",$circles);
    $cs_arr = array();
    foreach ($c_arr as $c) {
        $cs_arr[] = M("area")->where("id = ".$c)->getField("name");
    }
    $cs = implode(" ",$cs_arr);
    return $cs;
}


function getShopLogo($logo, $width = '') {
    if ($logo) {
        if ($width) {
            $logo = $width . "_" . $logo;
        }
        $logo = __APP__ . "/" . C("shopsFile") . "" . $logo . "";
    } else {
        $logo = __APP__ . "/Public/images/shop.gif";
    }
    return $logo;
}

function getUserAvatar($logo, $width = '') {
    if ($logo) {
        if ($width) {
            $logo = $width . "_" . $logo;
        }
        $logo = __APP__ . "/" . C("avatarFile") . "" . $logo . "";
    } else {
        $logo = __APP__ . "/Public/images/avatar.jpg";
    }
    return $logo;
}

function getOrdernum() {
    return date("YmdHis") . rand(1000, 9999);
}

function getPageKey($k) {
    $p = I("get.p", 1, 'int');
    return ($p - 1) * C("pagenum") + $k;
}

function getQrcode($url, $logo, $pic) {
    $value = $url; //二维码内容 
    $errorCorrectionLevel = 'L'; //容错级别 
    $matrixPointSize = 3; //生成图片大小 
//生成二维码图片 
    QRcode::png($value, 'Public/images/qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);

    $QR = 'Public/images/qrcode.png'; //已经生成的原始二维码图 

    if ($logo !== FALSE) {
        $QR = imagecreatefromstring(file_get_contents($QR));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR); //二维码图片宽度 
        $QR_height = imagesy($QR); //二维码图片高度 
        $logo_width = imagesx($logo); //logo图片宽度 
        $logo_height = imagesy($logo); //logo图片高度 
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        //重新组合图片并调整大小 
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
    }
    imagepng($QR, $pic);
    return $pic;
}

function cropPic($path, $savename, $width, $height) {
    $image = new \Think\Image();
    $image->open($path . $savename);
//   $image->open($path . "160_" . $savename);
//   $image->crop($size, $size,0,0)->save($path . "160_" . $savename);
    $action = strtolower(CONTROLLER_NAME);
    if ($action == 'goods') {
        $image->thumb(216, 179, \Think\Image::IMAGE_THUMB_FIXED)->save($path . "216_" . $savename);
        $image->thumb(210, 210, \Think\Image::IMAGE_THUMB_FIXED)->save($path . "210_" . $savename);
    } else {
        $image->thumb($width, $height, \Think\Image::IMAGE_THUMB_FIXED)->save($path . $savename);
    }
}

function threeLogin() {
    $arr = array(
        0 => array(
            "code" => "qq",
            "logo" => "qq"
        ),
        1 => array(
            "code" => "renren",
            "logo" => "qq"
        ),
        2 => array(
            "code" => "sina",
            "logo" => "qq"
        ),
    );
    return $arr;
}

function getChecked($ids, $id) {
    if (!empty($ids)) {
        $ids = explode(",", $ids);
        if (in_array($id, $ids)) {
            return "checked";
        }
    }
}

function getDisplay($ids, $id) {
    if (!empty($ids)) {
        $ids = explode(",", $ids);
        if (in_array($id, $ids)) {
            return "display:block";
        } else {
            return "display:none";
        }
    }
}

function isEqualChecked($id, $id2) {
    if ($id == $id2) {
        return "checked";
    }
}

function getSingleField($id, $table, $field, $word) {
    $info = M($table)->field($field)->where("id = " . $id . "")->find();
//    echo M($table)->getlastsql();exit;
    if ($info[$field] != '') {
        return $info[$field];
    } else {
        return $word;
    }
}

//公共函数
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
        if (false === $slice) {
            $slice = '';
        }
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    $fix = '';
    if (strlen($slice) < strlen($str)) {
        $fix = '...';
    }
    return $suffix ? $slice . $fix : $slice;
}

function tranTime($time) {
    $rtime = date("m-d H:i", $time);
    $htime = date("H:i", $time);
    $time = time() - $time;
    if ($time < 60) {
        $str = '刚刚';
    } elseif ($time < 60 * 60) {
        $min = floor($time / 60);
        $str = $min . '分钟前';
    } elseif ($time < 60 * 60 * 24) {
        $h = floor($time / (60 * 60));
        $str = $h . '小时前 ' . $htime;
    } elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time / (60 * 60 * 24));
        if ($d == 1)
            $str = '昨天 ' . $rtime;
        else
            $str = '前天 ' . $rtime;
    }
    else {
        $str = $rtime;
    }
    return $str;
}

function getIP() {
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = "无法获取！";
    }
    return $cip;
}

function getIpArea($ip) {
    $ipArr = new Org\Net\IpLocation('UTFWry.dat');
    $area = $ipArr->getlocation($ip);
    return $area;
}

function getMyIp($ip) {
    $ip = "221.204.169.45";
    $name = msubstr(getIpArea($ip), 0, 2, "utf-8", false);
    $area = getTableFile("area");
    foreach ($area as $v) {
        if (strstr($v['name'], $name)) {
            return $v['id'];
            break;
        }
    }
}

function sendMail($to, $name, $subject, $body = '', $attachment = null) {
    $config = getTableFile('config');
    $detail = json_decode(getTableField("emails", "three"), true);
//    print_r($detail);exit;
    vendor('phpmailer.class#phpmailer');
    $mail = new PHPMailer(); //PHPMailer对象
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug = 0;                     // 关闭SMTP调试功能
    $mail->SMTPAuth = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = '';                 // 使用安全协议
    $mail->Host = $detail['smpt'];  // SMTP 服务器
    $mail->Port = "";  // SMTP服务器的端口号
    $mail->Username = $detail['account'];  // SMTP服务器用户名
    $mail->Password = $detail['pwd'];  // SMTP服务器密码
    $mail->Subject = $subject; //邮件标题
    $mail->SetFrom($detail['account'], $config['title']);
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $config['title']);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

function getStar($star) {
    $span = "<span class='c-value-no c-value-4d" . intval($star) . "'><em></em></span>";
    return $span;
}

function getOneDot($num) {
    return sprintf("%.1f", $num);
}

function is_mobile() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $mobile_agents = array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi",
        "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio",
        "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu",
        "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ",
        "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi",
        "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "iphone", "ipod", "jbrowser", "kddi",
        "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo",
        "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-",
        "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia",
        "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-",
        "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo",
        "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank",
        "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit",
        "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin",
        "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce",
        "wireless", "xda", "xde", "zte");
    $is_mobile = 0;
    foreach ($mobile_agents as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = 1;
            break;
        }
    }
    return $is_mobile;
}

function objectToArray($e) {
    $e = (array) $e;
    foreach ($e as $k => $v) {
        if (gettype($v) == 'resource')
            return;
        if (gettype($v) == 'object' || gettype($v) == 'array')
            $e[$k] = (array) objectToArray($v);
    }
    return $e;
}

function utf8_strlen($string = null) {
// 将字符串分解为单元
    preg_match_all("/./us", $string, $match);
// 返回单元个数
    return count($match[0]);
}

function getStaticInfo($id, $table, $field) {
    if ($id > 0) {
        $lists = getTableFile($table);
        $arr = array();
        foreach ($lists as $k => $v) {
            if ($v['id'] == $id) {
                $arr = $v;
                break;
            }
        }
        if ($field != '') {
            return $arr[$field];
        } else {
            return $arr;
        }
    }
}

function getMinites($t) {
    $arr = explode(":", $t);
    return $arr[0] * 60 + $arr[1];
}

function getSendTime($t, $mtype = 0,$times='') {
    $sendtimeArr = array("11:00", "13:00", "15:00", "17:00");
    foreach ($sendtimeArr as $k3 =>$v) {
        if($k3 ==0){
            $rs2 = $v . "送餐";
        }
        $k = getMinites($v);
        if ($k == $t && $t > 0) {
            $rs = $v . "送餐";
            break;
        } else {
            if ($mtype == 0) {
                $rs[$k] = $v;
            }
        }
    }
    if($rs == '' && $times != ''){
        $times = explode(",",$times);
        $rs = "明天".$rs2;
    }
    return $rs;
}

function getMinSendTime($times) {
    $arr = explode(",", $times);
    $now_minutes = 60 * date("H") + date("i");
    foreach ($arr as $v) {
        if ($now_minutes < $v) {
            $sendtime = $v;
            break;
        }
    }
    return getSendTime($sendtime, 1,$times);
}
function getThreeField($three,$big,$small){
    $detail = json_decode($three[$big], true);
    return $detail[$small];
}
?>
